﻿using LogionDemo.Common.UserEventArgs;
using LogionDemo.Controls.Base;
using LogionDemo.Controls.Base.UserControls;
using LogionDemo.Models;
using LogionDemo.Models.Enums;

namespace LogionDemo.Controls
{
	public partial class RoleUC : BaseUC
	{
		private readonly AuditWithLoginBaseForm? _parentForm;
		private Dictionary<int, UserInfo> _dataCache = new();
		private List<UserInfo> _infos = new();
		private RegisterInfoContext _registerInfoContext = new();

		/// userinfo.id , rowNo
		private Dictionary<int, int> _rowIndex = new();

		public RoleUC()
		{
			InitializeComponent();
		}

		public RoleUC(AuditWithLoginBaseForm parentForm)
		{
			InitializeComponent();
			_parentForm = parentForm;
			parentForm.LoginStatusChangedEvent += ParentForm_LoginStatusChanged;
			Subscribe(new PropertyChangedObserver());
		}

		private void btnReadInfo_Click(object sender, EventArgs e)
		{
			ReadUserInfosAndUpdateUI();
		}

		private void btnUpdateInfo_Click(object sender, EventArgs e)
		{
			if (_parentForm == null) { return; }
			var userToken = _parentForm.UserToken;
			if (userToken == null) { return; }
			if (!_rowIndex.Any()) { return; }
			// 保存更改
			foreach (var kvp in _rowIndex)
			{
				var info = _infos.Where(info => info.UserInfoId == kvp.Key).First();
				info.UserRole = info.SelectedUserRole;
			}
			_registerInfoContext.SaveChanges();
			MessageBox.Show("更改成功！", "权限分配页面");
			// 日志更新
			OutputUserAuditLog(userToken);
			// 刷新表格
			ReadUserInfosAndUpdateUI();
		}

		private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
		{
			var rowIndex = e.RowIndex;
			var row = dataGridView1.Rows[rowIndex];
			var info = (UserInfo)row.DataBoundItem;
			if (!_dataCache.ContainsKey(info.UserInfoId)) { _dataCache.Add(info.UserInfoId, (UserInfo)info.Clone()); }
		}

		private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
		{
			var rowIndex = e.RowIndex;
			var row = dataGridView1.Rows[rowIndex];
			var info = (UserInfo)row.DataBoundItem;
			if (!_rowIndex.ContainsKey(info.UserInfoId)) { _rowIndex.Add(info.UserInfoId, e.RowIndex); }
		}

		private void OutputUserAuditLog(UserToken userToken)
		{
			foreach (var kvp in _rowIndex)
			{
				var row = dataGridView1.Rows[kvp.Value];
				var currentInfo = (UserInfo)row.DataBoundItem;
				if (_dataCache.TryGetValue(currentInfo.UserInfoId, out UserInfo? originalInfo))
				{
					if (!Equals(originalInfo.UserRole, currentInfo.UserRole))
					{
						// 记录审计日志 数据库还是log？
						if (userToken != null)
						{
							string propertyName = $"{currentInfo.UserName}的{nameof(currentInfo.UserRole)}";
							Publish(new PropertyChangedEventArgs(propertyName, originalInfo.UserRole, currentInfo.UserRole, userToken));
						}
					}
				}
			}
			_dataCache.Clear();
			_rowIndex.Clear();
		}

		private void ParentForm_LoginStatusChanged(object? sender, LoginStatusChangedEventArgs e)
		{
			UpdateUI();
		}

		private void ReadUserInfosAndUpdateUI()
		{
			dataGridView1.Columns.Clear();
			_infos = _registerInfoContext.UserInfos.Where(info => info.UserRole != UserRole.Admin).ToList();
			_infos.ForEach(info => info.SelectedUserRole = info.UserRole);
			dataGridView1.DataSource = _infos;
			DataGridViewComboBoxColumn? comboBoxColum = new DataGridViewComboBoxColumn()
			{
				DataPropertyName = "SelectedUserRole",
				HeaderText = "Modify",
				DataSource = Enum.GetValues(typeof(UserRole)).Cast<UserRole>()
							   .Where(role => role != UserRole.Admin)
							   .ToList(),
			};
			// 一些外观设计
			dataGridView1.Columns[nameof(UserInfo.PasswordSalt)].Visible = false;
			dataGridView1.Columns[nameof(UserInfo.SelectedUserRole)].Visible = false;
			dataGridView1.Columns[nameof(UserInfo.Password)].Visible = false;
			var a = dataGridView1.Columns[nameof(UserInfo.UserInfoId)].DisplayIndex = 0;
			dataGridView1.Columns.Add(comboBoxColum);
		}

		private void UpdateUI()
		{
			btnUpdateInfo.Enabled = _parentForm != null && _parentForm.UserToken != null && _parentForm.UserToken.Role == UserRole.Admin;
		}
	}
}